//
//  SearchViewController.m
//  FeiYang
//
//  Created by Maxwell Rose on 15/10/16.
//  Copyright © 2015年 feiyang. All rights reserved.
//
#import "ProductCell.h"
#import "SearchViewController.h"
#import "SearchHistoryCell.h"
#import "SearchHintCell.h"
#import "ProductModel.h"


//collectionViewCell的高度
#define kCellHeight     (((SCREEN_WIDTH - 4) * 0.5 / 1.48) + 24 + 32)

typedef NS_ENUM(NSInteger,SeachTableViewMode){
    SeachTableViewModeHistory,
    SeachTableViewModeHint
};
@interface SearchViewController ()<UITextFieldDelegate, UITableViewDelegate, UITableViewDataSource>

@property (strong, nonatomic)UITableView *tableView;

@property (assign, nonatomic)SeachTableViewMode tableMode;

@property (strong, nonatomic)NSMutableArray *historyArray;

@property (strong, nonatomic)NSMutableArray *hintArray;

@property (strong, nonatomic)NSMutableArray *dataSources;

@property (strong, nonatomic)UILabel *noDataView;

@property(nonatomic,strong)UIView *noNet;

@property (strong, nonatomic)UITapGestureRecognizer *tapGesture;

@property (strong, nonatomic)UITableView * searchTableView;

@property (nonatomic, assign)int idx;

@property (nonatomic,assign) int n;

@end

@implementation SearchViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
//    添加导航视图
    TopView *topView = [[TopView alloc]initWithFrame:CGRectMake(0.0f, 0.0f, SCREEN_WIDTH, 64.0f)];
    [self.view addSubview:topView];

//    添加搜索按钮
    UIButton * searchButton = [[UIButton alloc]initWithFrame:CGRectMake(SCREEN_WIDTH - 56, 20, 56, 44.0f)];
    [searchButton setTitle:@"搜索" forState:UIControlStateNormal];
    [searchButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [searchButton.titleLabel setFont:[UIFont systemFontOfSize:14]];
    [searchButton addTarget:self action:@selector(searchButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    searchButton.titleLabel.textAlignment = NSTextAlignmentRight;
    [topView addSubview:searchButton];
    
//    添加搜索框
    UITextField *searchField = [[UITextField alloc]initWithFrame:CGRectMake(69, 30, SCREEN_WIDTH - 69 - 56, 24)];
    searchField.placeholder = @"请输入您要搜索的产品";
    searchField.delegate = self;
    searchField.borderStyle = UITextBorderStyleNone;
    searchField.font = [UIFont systemFontOfSize:14];
    searchField.backgroundColor = [UIColor whiteColor];
    searchField.textColor = [UIColor colorWithWhite:0.000 alpha:0.300];
    searchField.layer.cornerRadius = 12;
    [searchField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    searchField.textColor = [UIColor colorWithWhite:0.000 alpha:0.300];
    
    
    UIImageView *leftView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"icon_search"]];
    CGRect rect = leftView.frame;
    rect.origin.x += 5;
    leftView.frame = rect;
    UIView *leftBackgroudView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, leftView.frame.size.width + 5, leftView.frame.size.height)];
    [leftBackgroudView addSubview:leftView];
    
    searchField.leftView = leftBackgroudView;
    searchField.leftViewMode = UITextFieldViewModeAlways;
    self.searchField = searchField;
    [topView addSubview:searchField];
    
//    添加返回按钮
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    backButton.frame =  CGRectMake(10.0f, 35.0f, 49.0f, 16.0f);
    [backButton addTarget:self action:@selector(backButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [backButton setImage:[UIImage imageNamed:@"icon_back"] forState:UIControlStateNormal];
    [topView addSubview:backButton];

    [self setUpTheSearchTableView];//初始化tableView
//    初始化tableview
    self.historyArray = [self historyArray];
    if (0 != self.historyArray.count) {
        [self swichTableViewMode:SeachTableViewModeHistory];
    }
    [self.view addSubview:self.tableView];
}

#pragma mark --------------表的刷新与加载更多
-(void)refreshTheTableView
{
    _idx = 0;
    _n = 0;
    
    [self getHttpData];
}
- (void)AddtoTheProjectTableView
{
    [self getHttpData];
}
- (void)getHttpData
{
    _noDataView.hidden = TRUE;
    _noNet.hidden = TRUE;
    
    if (!_dataSources) {
        _dataSources = [NSMutableArray array];
    }
    _n++;
    
    //发送网络请求获取视频列表 
    NSDictionary *parameter = @{@"key":self.searchField.text,@"page.size":[NSNumber numberWithInt:10],@"page.pn":[NSNumber numberWithInt:_idx + 1]};
    [AppGlobalClass PostDataWithNSstring:GETSEARCHPRODUCTLIST withDictionary:parameter success:^(NSDictionary *dictionary) {
        
        if ([[dictionary objectForKey:@"success"] isEqualToNumber:@YES])
        {
            [self.searchTableView.header endRefreshing];
            [self.searchTableView.footer setState:MJRefreshStateIdle];
            [self.searchTableView.footer endRefreshing];
            
            if(_idx == 0)
            {
                [_dataSources removeAllObjects];
            }
            
            
            NSArray *dataArray = [dictionary objectForKey:@"responseData"];
            NSDictionary *dataDict = [dataArray firstObject];
            
            if([[dataDict objectForKey:@"pages"] intValue] > _idx)
            {
                
                NSMutableArray *listArray = [[[dictionary objectForKey:@"responseData"]firstObject] objectForKey:@"rows"];
                
                for (NSDictionary * dataDict in listArray)
                {
                    ProductModel * model = [[ProductModel alloc]initWithDictionary:dataDict];
                    [_dataSources addObject:model];
                }
                _idx++;
                
                [self.searchTableView reloadData];
                
                if(_dataSources.count < 10)
                {
                    [self.searchTableView.footer endRefreshingWithNoMoreData];
                }
                else
                {
                    if (_n<2) {
                        
                        self.searchTableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(AddtoTheProjectTableView)];
                        
                    }
                    
                }
            }
            else
            {
                if (self.dataSources.count==0) {
                    
                    //                    无数据
                    self.noDataView.hidden = FALSE;
                    
                }
                
                [self.searchTableView.footer endRefreshingWithNoMoreData];
            }
            
        }else{
            //没有真确返回
            [self.dataSources removeAllObjects];
            [_searchTableView reloadData];
            _noDataView.hidden = FALSE;
            
            [self.searchTableView.header endRefreshing];
            [self.searchTableView.footer setState:MJRefreshStateIdle];
            [self.searchTableView.footer endRefreshing];
        }
        
    } failure:^(NSError *error) {
        _noDataView.hidden = FALSE;
        [_dataSources removeAllObjects];
        [_searchTableView reloadData];
        [self.searchTableView.header endRefreshing];
        [self.searchTableView.footer setState:MJRefreshStateIdle];
        [self.searchTableView.footer endRefreshing];
    } networkerror:^(NSString *networkerror) {
        _noNet.hidden = FALSE;
        [_dataSources removeAllObjects];
        [_searchTableView reloadData];
        [self.searchTableView.header endRefreshing];
        [self.searchTableView.footer setState:MJRefreshStateIdle];
        [self.searchTableView.footer endRefreshing];
    }];

}

/**
 *  切换实时搜索或者历史
 *
 *  @param mode SeachTableViewModeHistory or SeachTableViewModeHint
 */
- (void)swichTableViewMode:(SeachTableViewMode)mode{
    self.tableMode = mode;
    if (mode == SeachTableViewModeHistory) {
        [self addClearHistoryButtonView];
    }else{
        self.tableView.tableHeaderView = nil;
    }
    [self.tableView reloadData];
    [self.view bringSubviewToFront:self.tableView];
}

#pragma mark - searchTableView 初始化
- (UITableView *)searchTableView{
    if (_searchTableView == nil) {
        _searchTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT - 64) style:UITableViewStylePlain];
        [self.view addSubview: _searchTableView];
        [_searchTableView addSubview:self.noNet];
        [_searchTableView addSubview:self.noDataView];
    }
    return _searchTableView;
}
/**
 searchTableView
*/
- (void)setUpTheSearchTableView{
    
    self.searchTableView.delegate = self;
    self.searchTableView.dataSource = self;
    self.searchTableView.backgroundColor = [UIColor whiteColor];
    [_searchTableView registerClass:[ProductCell class] forCellReuseIdentifier:@"cell"];
    _searchTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.searchTableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self refreshTheTableView];
    }];

}
/**
 *  添加清空历史按钮
 */
- (void)addClearHistoryButtonView{
    if (!self.tableView.tableHeaderView) {
        UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 50)];
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(SCREEN_WIDTH - 120, 9, 120, 30);
        [button setTitleColor:[UIColor hexStringToColor:@"#969494"] forState:UIControlStateNormal];
//        [button setTitleColor:kColorOrangePressed forState:UIControlStateHighlighted];
        button.titleLabel.font = [UIFont systemFontOfSize:15];
        [button setTitle:@"清空历史" forState:UIControlStateNormal];
        [button addTarget:self action:@selector(clearHistory:) forControlEvents:UIControlEventTouchUpInside];
        [button setImage:[UIImage imageNamed:@"search_history_del"] forState:UIControlStateNormal];
        [view addSubview:button];
        
        self.tableView.tableHeaderView = view;
    }
}

/**
 *  懒加载tableview
 *
 *  @return UITableView
 */
- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT - 64) style:UITableViewStylePlain];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
//        _tableView.backgroundColor = kColorGrayBackground;
        [_tableView registerClass:[SearchHistoryCell class] forCellReuseIdentifier:@"SearchHistoryCell"];
        [_tableView registerClass:[SearchHintCell class] forCellReuseIdentifier:@"SearchHintCell"];
        
        self.hintArray = [NSMutableArray array];
        self.historyArray = [NSMutableArray array];
        
    }
    return _tableView;
}

#pragma mark - UI交互处理
- (void)searchButtonAction:(UIButton *)btn{
    [self.view bringSubviewToFront:self.searchTableView];
    NSMutableArray *history = [self historyArray];
    if (![history containsObject:self.searchField.text]) {
        //历史中不含此搜索字符
        if (![self.searchField.text isEqualToString:@""]) {
            [history insertObject:self.searchField.text atIndex:0];
        }
    }else{
        //包含
        [history exchangeObjectAtIndex:0 withObjectAtIndex:[history indexOfObject:self.searchField.text]];
    }
    
    NSLog(@" %d | %s | %@",__LINE__,__FUNCTION__,history);
    [[NSUserDefaults standardUserDefaults] setObject:history forKey:@"searchHistroyArray"];
    [self.searchTableView.header beginRefreshing];
    [self.searchField resignFirstResponder];

//    [self refresh];
}

- (void)backButtonAction:(UIButton *)btn{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)textFieldDidBeginEditing:(UITextField *)textField{
    if (!_tapGesture) {
        _tapGesture = [[UITapGestureRecognizer alloc]init];
        [_tapGesture addTarget:self action:@selector(resignKeyBoard)];
    }
    [self.view addGestureRecognizer:_tapGesture];
    NSLog(@" %d | %s ",__LINE__,__FUNCTION__);
}

- (void)textFieldDidEndEditing:(UITextField *)textField{
    [self.view removeGestureRecognizer:_tapGesture];
}

// called when 'return' key pressed. return NO to ignore.
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [self.searchField resignFirstResponder];
    [self searchButtonAction:nil];
    return YES;
    
}

- (void)textFieldDidChange:(UITextField *) TextField{
    if (0 == TextField.text.length) {
        [self swichTableViewMode:SeachTableViewModeHistory];
    }else{
        [self swichTableViewMode:SeachTableViewModeHistory];
//        暂时无模糊搜索提示
//        [self.hintArray addObject:TextField.text];
//        [self swichTableViewMode:SeachTableViewModeHint];
    }
}

- (void)clearHistory:(UIButton *)btn{
    [self saveHistoryArray:[NSArray array]];
    [self.tableView reloadData];
}
- (void)noResultButtonAction:(UIButton *)btn{
    [self.searchTableView.header beginRefreshing];
}

- (void)resignKeyBoard{
    [self.searchField resignFirstResponder];
}
#pragma mark - 数据持久化
/**
 *  获取存储的历史搜索记录
 *
 *  @return 包含历史搜索记录的可变数组
 */
- (NSMutableArray *)historyArray{
    NSMutableArray *history = [(NSMutableArray *)[[NSUserDefaults standardUserDefaults] objectForKey:@"searchHistroyArray"] mutableCopy];
    if (!history) {
        history = [NSMutableArray array];
    }
    return history;
}

/**
 *  存储搜索记录
 *
 *  @param historyArray 包含记录的数组
 */
- (void)saveHistoryArray:(NSArray *)historyArray{
    [[NSUserDefaults standardUserDefaults] setObject:historyArray forKey:@"searchHistroyArray"];
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (tableView == _tableView) {
        if (self.tableMode == SeachTableViewModeHistory) {
            return self.historyArray.count;
        }else{
            //SeachTableViewModeHint
            return self.hintArray.count;
        }
    }else
    {
        return 1;
    }
    
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (tableView == _tableView) {
        return 1;
    }else
    {
        return _dataSources.count;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView == _tableView)
    {
        if (self.tableMode == SeachTableViewModeHistory) {
            SearchHistoryCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SearchHistoryCell" forIndexPath:indexPath];
            cell.textLabel.text = self.historyArray[indexPath.row];
            return cell;
            
        }else{
            //SeachTableViewModeHint
            SearchHintCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SearchHintCell" forIndexPath:indexPath];
            cell.textLabel.text = self.hintArray[indexPath.row];
            return cell;
            
        }

    }else
    {
        ProductCell * cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
        ProductModel * model = _dataSources[indexPath.section];
        cell.productTitle.text = model.pname;
        cell.productNumberLabel.text = [NSString stringWithFormat:@"编码：%@",model.pcode];
        float revate = ([model.revrate intValue])/10.0;
        [cell.advanceView setTheTitle1:@"预期收益" andTitle2:[NSString stringWithFormat:@"%.2f%%",revate]];
        [cell.timeView setTheTitle1:@"产品期限" andTitle2:[NSString stringWithFormat:@"%@天",model.revperiod]];
        
        if ([[NSString stringWithFormat:@"%@",model.paymethod] isEqualToString:@"1"]) {
            [cell.accessView setTheTitle1:@"付息方式" andTitle2:@"一次性"];
        }else if
            ([[NSString stringWithFormat:@"%@",model.paymethod] isEqualToString:@"4"])
        {
            [cell.accessView setTheTitle1:@"付息方式" andTitle2:@"按季付息"];
        }else
        {
            [cell.accessView setTheTitle1:@"付息方式" andTitle2:@"按半年付息"];
        }
        
      [cell.statusView setTheTitle1:@"产品状态" andTitle2:@"在售"];
       
        
        return cell;

        
    }

}
#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView == _tableView) {
        return 48;
    }else
    {
        return 84;
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (tableView == _tableView)
    {
        if (section == 0) {
            return 0.01;
        }
        return 4;

    }else
    {
        return 0;
    }
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if (tableView == _tableView) {
        if (section == _dataSources.count - 1) {
            return 0;
        }
        return 4;
    }
    else
    {
        return 0;
    }
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView == _tableView)
    {
        if (self.tableMode == SeachTableViewModeHistory) {
            self.searchField.text = self.historyArray[indexPath.row];
            
        }else{
            //SeachTableViewModeHint
            self.searchField.text = self.hintArray[indexPath.row];
        }
    }
    
}


//没网提示
#pragma mark - 无网提示
-(UIView *)noNet
{
    if (!_noNet) {
        _noNet = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 200, 200)];
        _noNet.center = CGPointMake(_searchTableView.center.x, _searchTableView.center.y - 64 - 32);
        _noNet.hidden = TRUE;
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(0, 0, 200, 200);
        [button setImage:[UIImage imageNamed:@"img_nonetwork"] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(noResultButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 200 - 40, 200, 44)];
        label.text = @"网络不通\n点击重新搜索";
        label.font = [UIFont systemFontOfSize:15.0f];
        label.textAlignment = NSTextAlignmentCenter;
        label.numberOfLines = 0;
        label.textColor = [UIColor colorWithWhite:0.000 alpha:0.540];
        [_noNet addSubview:label];
        [_noNet addSubview:button];
    }
    return _noNet;
}
-(UILabel *)noDataView
{
    if (!_noDataView) {
        _noDataView = [[UILabel alloc] initWithFrame:CGRectMake(0.0f, 20.f, SCREEN_WIDTH, 24.0f)];
        _noDataView.text = @"未搜到相关结果";
        _noDataView.hidden = TRUE;
        _noDataView.textAlignment = NSTextAlignmentCenter;
        _noDataView.textColor = [UIColor colorWithWhite:0.000 alpha:0.540];
    }
    return _noDataView;
}

@end
